// +----------------------------------------------------------------------
// | BossHongshi [鸿时互娱管理系统]
// +----------------------------------------------------------------------
// | Copyright (c) 2018 http://www.hongshihuyu.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: wgh
// +----------------------------------------------------------------------

const fly=require("flyio")
const HashMap = require('hashmap');
module.exports = class extends think.Controller {
  /**
   * index action
   * @return {Promise} []
   */
  indexAction() {
    // auto render template file index_index.html
    return this.display();
  }
  async cloaAction() {
    // 订单在规定时间为付款自动作废执行方法
    // 禁止 URL 访问该 Action
    if (!this.isCli) {
      const error = this.controller('cmswing/error');
      return error.noAction('only invoked in cli mode！');
    }

    // 查询未付款，未作废的订单的订单
    const map = {
      pay_status: 0,
      status: 2,
      create_time: ['<', (new Date().getTime() - (Number(this.config('setup.ORDER_DELAY')) * 60000))],
      type: 0
    };
    const order = await this.model('order').where(map).field('id').select();
    if (!think.isEmpty(order)) {
      for (const v of order) {
        await this.model('order').where({id: v.id}).update({status:6, admin_remark: '规定时间未付款系统自动作废'});
        // 释放库存
        //await this.model('cmswing/order').stock(v.id, false);
      }
    }

    // think.logger.debug(new Date(), '订单作废任务执行时间');
    // this.end();
    return this.body = '';
  }
  
  //关闭保险柜房间
  async closbAction() {
	    // 订单在规定时间为付款自动作废执行方法
	    // 禁止 URL 访问该 Action
	    if (!this.isCli) {
	      const error = this.controller('cmswing/error');
	      return error.noAction('only invoked in cli mode！');
	    }
	    console.log('作废的保险柜房间处理流程 -- 开始:');
	    // 查询未处理，未作废的保险柜房间
	    const map = {
//	      status: 0,
	      status: ['IN', [0,1]],
	      create_time: ['<', (new Date().getTime() - (Number(this.config('setup.SAFEBOX_DELAY')) * 60000))]
	    };
	    console.log('查询超时未处理的保险柜房间 -- 开始 :');
	    const safebox = await this.model('safebox').where(map).field('id,uid,pid,deposit_count,catalog,password').select();
	    console.log('获取超时未处理的保险柜房间数量  --:'+safebox.length);
	    fly.config.timeout=10000;
  		fly.config.parseJson=true;
  		
	    if (!think.isEmpty(safebox)) {
	      console.log('超时未处理的保险柜房间更改为作废状态  --开始:');
	      for (const v of safebox) {
	    	//http://47.97.119.70:5166/GameSupport/dn?cmd=safeTimeout&uid=28&roomId=10000&type=1&num=100&sign=password
	    	const url='http://47.97.119.70:5166/GameSupport/dn?cmd=safeTimeout&uid='+v.uid+'&roomId='+v.password+'&type='+v.catalog+'&num='+v.deposit_count+'&sign=password';
	  		let ret = await fly.get(url);
	  		if(v.catalog=='2'){
	  			const mdres = await this.model('member').where({id:v.pid}).increment('coin_count',v.deposit_count);
	  		}
	        await this.model('safebox').where({id: v.id}).update({status:-1,admin_remark: '规定时间未处理系统自动作废'});
	      }
	      console.log('超时未处理的保险柜房间更改为作废状态  --结束:');
	    }
	    console.log('作废的保险柜房间处理流程 -- 结束:');
//	    think.logger.debug(new Date(), '房间作废任务执行时间');
	    return this.body = '';
	  }
  
  //分润计算(清算)
  async profitAction() {
	    // 禁止 URL 访问该 Action
	    if (!this.isCli) {
	      const error = this.controller('cmswing/error');
	      return error.noAction('only invoked in cli mode！');
	    }
	    console.log('分润处理流程 -- 开始!');
	    // 查询未分润记录
	    var deadline = await this.model('setup').where({name:'PROFIT_DEADLINE'}).getField('value', true);
		console.log('上次分润处理截至时间--:'+this.moment(deadline*1000).format('YYYY-MM-DD HH:mm:ss'));
		var timeperiod = await this.model('setup').where({name:'PROFIT_TIMEPERIOD'}).getField('value', true);
		console.log('本次分润处理时间跨度为--:'+timeperiod+"秒");
		var hoursec = parseInt(deadline)+parseInt(timeperiod);
		var newdeadline = hoursec;
		console.log('增加时间区间后时间--:'+this.moment(hoursec*1000).format('YYYY-MM-DD HH:mm:ss'));
		let scorelog = this.mongoose('jb_scorelog', 'mongoose'); // use `mongoose` adapter type
		//let scorelogdata  = await scorelog.find({$and: [{reffer_id:{$ne:0}},{reffer_id:{$ne:1000001}},{create_time:{$gt:1538105016,$lte:1545494498}}]}).sort({'create_time':1}).lean().exec();
		let scorelogdata  = await scorelog.find({$and: [{reffer_id:{$ne:0}},{reffer_id:{$ne:1000001}},{create_time:{$gt:parseInt(deadline),$lte:parseInt(hoursec)}}]}).sort({'create_time':1}).lean().exec();
	    
		if(!think.isEmpty(scorelogdata)){
	    	var len = scorelogdata.length;
	    	console.log('获取数据记录数为--:'+len);
	    	//newdeadline = scorelogdata[len-1].create_time;
	    	var start_time= this.moment(deadline*1000).format('lll');
	    	var end_time= this.moment(newdeadline*1000).format('lll');
	    	var map = new HashMap();
	     	for (const v of scorelogdata) {
	     		if(!map.has(v.uid)){
	     			let profitObj = {}; 
	     			profitObj.uid = v.uid;
	     			profitObj.starttime = v.create_time;
	     			profitObj.endtime = v.create_time;
	     			profitObj.reffer_id = v.reffer_id;
	     			profitObj.cost = v.cost;
	     			profitObj.ctime = v.ctime;
	     			profitObj.room_id=v.room_id;
	     			profitObj.id = v.id;
	     			profitObj.lid = v.id;
	     			profitObj.num = 1;
	     			map.set(v.uid,profitObj);
	     		}else{
	     			var profitObj = map.get(v.uid);
	     			profitObj.endtime = v.create_time;
	     			profitObj.cost = parseInt(profitObj.cost)+parseInt(v.cost);
	     			profitObj.ctime = v.ctime;
	     			var room_id_str = profitObj.room_id.toString();
	     			var vroom_id = v.room_id.toString();
	     			if(room_id_str.indexOf(vroom_id)<0){
	     			   profitObj.room_id=profitObj.room_id+","+v.room_id;
	     			}
	     			profitObj.id = profitObj.id+","+v.id;
	     			profitObj.lid = v.id;
	     			profitObj.num = parseInt(profitObj.num)+1;
	     		}
	     	}
	     	
	     	var key = map.keys();
	     	for (var i in key){
	     		var v = map.get(key[i]);
	     	    const member = await this.model('member').where({proxy_id:v.reffer_id}).find();
	     	   
		       if(!think.isEmpty(member)&&member.is_admin!=1){
		    		  const rebate = await this.model('rebate').where({rebate_no:'con_coin',is_default:1}).find();
		    		  const zoning = JSON.parse(rebate.zoning);
		    		  if (!think.isEmpty(zoning)){
		    			  console.log('---存在金币消耗分润配置，取具体分润规则开始-----!');
		    			  let area = JSON.parse(member.area);
		    		      for (const val of zoning) {
		    		    	  if (in_array(area[0], JSON.parse(val.area))) {
		    		        	if(!think.isEmpty(val.f_ratio)){
		  	    		    	 console.log(v.uid+'金币消耗，为 '+member.id+' 向上一级分润开始-----!');
		  		        		  let fp_amount =parseFloat(Number(v.cost) * Number(val.f_ratio)/10000).toFixed(4);
		  		        		  
		  		        		  if(fp_amount>parseFloat(0.0000)){
		  		        			const fplog = {
				   			                user_id:member.id,
				   			                proxy_id:member.proxy_id,
				   			                type:3,
				   			                amount:fp_amount,
				           			        amount_log:fp_amount,
				           			        status:0,
				           			        origin_id:v.id,
				   			                create_time: new Date().valueOf(),
				   			                act_id:v.uid,
				   			                room_id:v.room_id,
				   			                note: `通过游戏ID： [${v.uid}] 在 [${start_time} 至 ${end_time}]期间，玩牌 ${v.num}局，获得分润：${fp_amount}`
				   			             };
				   			          await this.model('profit_log').add(fplog);
				   			         console.log(v.uid+' 金币消耗 ,'+member.id+'分润金额为：'+fp_amount+',向上一级分润结束-----!');
		  		        		  }else{
		  		        			console.log(v.uid+'金币消耗,'+member.id+'分润金额小于0.00 ，不分润,向上一级分润结束-----!');
		  		        		  }
		   			       
		   			             if(!think.isEmpty(val.s_ratio)){
		  		        			const smember = await this.model('member').where({proxy_id:member.ia_uname}).find();
		  		        			if(!think.isEmpty(smember)&&smember.is_admin!=1){
		  		        				console.log(v.uid+'金币消耗，为 '+smember.id+' 向上二级分润开始-----!');
		  		        				let sp_amount =parseFloat(Number(v.cost) * Number(val.s_ratio)/10000).toFixed(4);
		  		        				if(sp_amount>parseFloat(0.0000)){
			  		        				const splog = {
				          			                user_id:smember.id,
				          			                proxy_id:smember.proxy_id,
				          			                type:3,
				          			                amount:sp_amount,
				                  			        amount_log:sp_amount,
				                  			        status:0,
				                  			        origin_id:v.id,
				          			                create_time: new Date().valueOf(),
				          			                act_id:v.uid,
				          			                room_id:v.room_id,
				          			                note: `通过游戏ID： [${v.uid}] 在 [${start_time} 至 ${end_time}]期间，玩牌 ${v.num}局，获得分润：${sp_amount}`
				          			            };
				          			            await this.model('profit_log').add(splog);
				          			        console.log(v.uid+' 金币消耗 ,'+smember.id+'分润金额为：'+sp_amount+',向上二级分润结束-----!');
		  		        				}else{
		  		        					console.log(v.uid+'金币消耗,'+smember.id+'分润金额小于0.00 ，不分润,向上二级分润结束-----!');
		  		        				}
		  		        			}
		      			            if(!think.isEmpty(val.t_ratio)){
		  			        			const tmember = await this.model('member').where({proxy_id:smember.ia_uname}).find();
		  			        			if(!think.isEmpty(tmember)&&tmember.is_admin!=1){
		  			        				console.log(v.uid+'金币消耗，为 '+tmember.id+' 向上三级分润开始-----!');
		  			        				let tp_amount =parseFloat(Number(v.cost) * Number(val.t_ratio)/10000).toFixed(4);
		  			        				if(tp_amount>parseFloat(0.0000)){
		  			        					const tplog = {
				              			                user_id:tmember.id,
				              			                proxy_id:tmember.proxy_id,
				              			                type:3,
				              			                amount:tp_amount,
				                      			        amount_log:tp_amount,
				                      			        status:0,
				                      			        origin_id:v.id,
				              			                create_time: new Date().valueOf(),
				              			                act_id:v.uid,
				              			                room_id:v.room_id,
				              			                note: `通过游戏ID： [${v.uid}] 在 [${start_time} 至 ${end_time}]期间，玩牌 ${v.num}局，获得分润：${tp_amount}`
				              			        };
				              			        await this.model('profit_log').add(tplog);
				              			      console.log(v.uid+' 金币消耗 ,'+tmember.id+'分润金额为：'+tp_amount+',向上三级分润结束-----!');
		  			        				}else{
		  			        				 console.log(v.uid+'金币消耗,'+tmember.id+'分润金额小于0.00 ，不分润,向上三级分润结束-----!');
		  			        				}
		  			        			}
		  			        		}
		  		        		 }
		  		        	  }
		    		        }//具体分润 for
		    		    }//230
		    	  }//145
		       }
	     	}//for end
	    }else {
	    	console.log('没有获取数据记录--:');
	    }
	    
	    if (!think.isEmpty(newdeadline)) {
	    	console.log("更新分润处理截至时间为:"+newdeadline+" 时间格式化后:"+this.moment(newdeadline*1000).format('YYYY-MM-DD HH:mm:ss'));
    		await this.model('setup').where({name:'PROFIT_DEADLINE'}).update({value:newdeadline});
    	}
	    
	    console.log('分润处理流程  -- 结束!');
	    return this.body = '';
	  }
  
  //分润计算(结算)
  async settlementAction() {
	    // 禁止 URL 访问该 Action
	    if (!this.isCli) {
	      const error = this.controller('cmswing/error');
	      return error.noAction('only invoked in cli mode！');
	    }
	    console.log('分润结算流程 -- 开始!');
	    // 查询未结算分润记录
	    const map = {
	    		status:0
	    };
	    map.create_time = {'>=': new Date(GetDateStr(-1) + ' ' + '00:00:00').getTime(), '<=': new Date(GetDateStr(-1) + ' ' + '23:59:59').getTime()};
	    
	    const profit_log_list = await this.model('profit_log').where(map).select();
	    for (let v of profit_log_list) {
	    	const increment = await this.model('member').where({id:v.user_id}).increment('amount',v.amount);
	    	if(!think.isEmpty(increment)){
	    		const update = await this.model('profit_log').where({id:v.id}).update({status:1,settle_time:new Date().valueOf()});
		    	if(think.isEmpty(update)){
		    	  await this.model('member').where({id:v.user_id}).decrement('amount',v.amount);
		    	}
	    	}
	    }
	    
	    console.log('分润结算流程  -- 结束!');
	    return this.body = '';
	  }
};
